package ace.module.captcha.core.impl.manager.repository.impl;

import ace.module.captcha.core.impl.dao.entity.CaptchaApplication;
import ace.module.captcha.core.impl.dao.repository.CaptchaApplicationRepository;
import ace.module.captcha.core.impl.manager.repository.CaptchaApplicationMgrRepository;
import com.alicp.jetcache.anno.CacheInvalidate;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.CacheUpdate;
import com.alicp.jetcache.anno.Cached;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * @author caspar
 * @date 2023/3/21 9:06
 */
@AllArgsConstructor
@Component
public class CaptchaApplicationMgrRepositoryImpl implements CaptchaApplicationMgrRepository {
  public static final String CACHE_AREA = "captcha_application_biz_type";
  public static final String CACHE_CAPTCHA_ITEM = "captcha:application:biz:type";
  private final CaptchaApplicationRepository captchaApplicationRepository;

  @Cached(area = CACHE_AREA, name = CACHE_CAPTCHA_ITEM, cacheType = CacheType.BOTH, key = "args[0]")
  @Override
  public CaptchaApplication getById(Long id) {
    return this.captchaApplicationRepository.findById(id).orElse(null);
  }

  @CacheUpdate(area = CACHE_AREA, name = CACHE_CAPTCHA_ITEM, key = "args[0].id", value = "#result")
  @Override
  public CaptchaApplication save(CaptchaApplication item) {
    Assert.notNull(item, "item can't be null");
    if (this.captchaApplicationRepository.existsById(item.getId())) {
      this.captchaApplicationRepository.updateById(item);
    } else {
      this.captchaApplicationRepository.insert(item);
    }
    return item;
  }

  @CacheInvalidate(area = CACHE_AREA, name = CACHE_CAPTCHA_ITEM, key = "args[0]")
  @Override
  public void remove(Long id) {
    this.captchaApplicationRepository.deleteById(id);
  }
}
